/*
 * @lc app=leetcode.cn id=2 lang=typescript
 *
 * [2] 两数相加
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

//  思路：迭代、dummy节点
//  每次创建一个新的节点记录值

//  复杂度：O(n) O(1)

function addTwoNumbers(l1: ListNode | null, l2: ListNode | null): ListNode | null {
    let newHead = new ListNode()
    let prev = newHead, p1 = l1, p2 = l2, carry = 0
    while (p1 || p2) {
        let curr = new ListNode()
        let value = (p1 ? p1.val : 0) + (p2 ? p2.val : 0)
        curr.val = (value + carry) % 10
        carry = value > 9 ? 1 : 0
        prev.next = curr
        prev = curr
        if (p1) p1 = p1.next
        if (p2) p2 = p2.next
    }
    if (carry > 0) prev.next = new ListNode(1)

    return newHead.next
};
// @lc code=end

import { ListNode } from "./type"
const l1 = new ListNode(2, new ListNode(4, new ListNode(3)))
const l2 = new ListNode(5, new ListNode(6, new ListNode(4)))
console.log(ListNode.printList(addTwoNumbers(l1, l2)))
